<template>
  <view class="progress-container">
    <!-- 时间显示 -->
    <view class="time-display">
      <text class="time-text">{{ formatTime(currentTime) }}</text>
      <text class="time-text">{{ formatTime(duration) }}</text>
    </view>

    <!-- 自定义进度条 -->
    <view 
      class="custom-progress" 
      @click="handleProgressClick"
    >
      <!-- 缓冲条 -->
      <view 
        class="buffer-bar" 
        :style="{ width: `${bufferPercent}%` }"
      ></view>
      
      <!-- 进度条 -->
      <view 
        class="progress-bar" 
        :style="{ width: `${progressPercent}%` }"
      ></view>
      
      <!-- 自定义滑块 -->
      <view 
        class="slider-thumb" 
        :style="{ left: `${progressPercent}%` }"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      ></view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, computed, watch, type CSSProperties } from 'vue'

interface Props {
  currentTime: number  // 当前时间（秒）
  duration: number     // 总时长（秒）
  bufferPercent: number // 缓冲百分比 0-100
}

const props = withDefaults(defineProps<Props>(), {
  currentTime: 0,
  duration: 0,
  bufferPercent: 0
})

type EmitType = {
  (e: 'drag-start'): void
  (e: 'drag-move', time: number): void
  (e: 'drag-end', time: number): void
}

const emit = defineEmits<EmitType>()

// 触摸交互相关状态
const isDragging = ref(false)
const containerWidth = ref(0)
const containerLeft = ref(0)

// 进度百分比计算
const progressPercent = computed(() => {
  return props.duration > 0 
    ? Math.min((props.currentTime / props.duration) * 100, 100)
    : 0
})

// 时间格式化显示
const formatTime = (seconds: number): string => {
  const minutes = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

// 获取容器尺寸
interface ContainerRect {
  width: number
  left: number
}

const getContainerRect = async (): Promise<void> => {
  const query = uni.createSelectorQuery()
  try {
    const rect = await new Promise<ContainerRect>((resolve) => {
      query.select('.custom-progress').boundingClientRect((res) => {
        resolve(res as ContainerRect)
      }).exec()
    })
    containerWidth.value = rect.width
    containerLeft.value = rect.left
  } catch (error) {
    console.error('获取容器尺寸失败:', error)
  }
}

// 触摸事件处理
const handleTouchStart = async (e: TouchEvent): Promise<void> => {
  await getContainerRect()
  isDragging.value = true
  emit('drag-start')
}

const handleTouchMove = (e: TouchEvent): void => {
  if (!isDragging.value) return
  
  const touch = e.touches[0]
  if (!touch) return
  
  const touchX = touch.pageX - containerLeft.value
  const percent = Math.min(Math.max(touchX / containerWidth.value, 0), 1)
  const newTime = percent * props.duration
  
  emit('drag-move', newTime)
}

const handleTouchEnd = (): void => {
  isDragging.value = false
  emit('drag-end', props.currentTime)
}

// 点击进度条跳转
const handleProgressClick = async (e: TouchEvent): Promise<void> => {
  await getContainerRect()
  const touch = e.touches[0]
  if (!touch) return
  
  const touchX = touch.pageX - containerLeft.value
  const percent = Math.min(Math.max(touchX / containerWidth.value, 0), 1)
  const newTime = percent * props.duration
  emit('drag-end', newTime)
}
</script>

<style lang="scss" scoped>
.progress-container {
	width: 100%;
  padding: 20rpx 40rpx;
}

.time-display {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
  
  .time-text {
    font-size: 24rpx;
    color: #666;
  }
}

.custom-progress {
  height: 4rpx;
  background: #e0e0e0;
  border-radius: 2rpx;
  position: relative;
}

.buffer-bar {
  position: absolute;
  height: 100%;
  background: #d1d1d1;
  border-radius: 2rpx;
  transition: width 0.3s ease;
}

.progress-bar {
  position: absolute;
  height: 100%;
  background: #ec4141;
  border-radius: 2rpx;
  transition: width 0.2s linear;
  z-index: 2;
}

.slider-thumb {
  position: absolute;
  width: 28rpx;
  height: 28rpx;
  background: #fff;
  border: 4rpx solid #ec4141;
  border-radius: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 3;
  transition: 
    left 0.2s linear,
    transform 0.1s ease;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.15);

  &:active {
    transform: translate(-50%, -50%) scale(1.2);
  }
}
</style>